﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Medianamik.UI.Controls
{
    [ToolboxData("<{0}:GridColumnFilter runat=server></{0}:GridColumnFilter>")]
    public class GridColumnFilter : CompositeControl  
    {

        private TextBox _txt;

        private static readonly object _filterEvent = new object();
        public event Action<object, GridColumnFilterEventArgs>  Filter
        {
            add
            {
                Events.AddHandler(_filterEvent, value);
            }
            remove
            {
                Events.RemoveHandler(_filterEvent, value); 
            }
        }

        protected virtual void OnFilter(GridColumnFilterEventArgs args)
        {
            var eh = Events[_filterEvent] as Action<object, GridColumnFilterEventArgs>;
            if (eh != null)
            {
                eh(this, args);
            }
        }
               
        [Bindable(true)]
        public string Value
        {
            get
            {
                return ViewState["Value"] as string ?? string.Empty;
            }

            set
            {
                ViewState["Value"] = value;
            }
        }
               
        protected override void CreateChildControls()
        {
            _txt = new TextBox();
            Controls.Add(_txt);
            _txt.Text = Value;
            _txt.ID = this.ID;
            _txt.CssClass = "TxtBox";
                        

            Button bt = new Button();
            Controls.Add(bt);
            bt.ID = "btnFilter";
            bt.CssClass = "BtFiltrer";
            bt.Click += new EventHandler(bt_Click);

           

            var script = @"
$(function() {
    $('#" + _txt.ClientID + @"').defaultButton('#" + bt.ClientID + @"');
});";
            ScriptManager.RegisterStartupScript(this, this.GetType(), _txt.ClientID, script, true); 

        }
               

        void bt_Click(object sender, EventArgs e)
        {
            Value = _txt.Text;
            OnFilter(new GridColumnFilterEventArgs(this.ID , Value));
        }
                       
    }

    public class GridColumnFilterEventArgs : EventArgs
    {

        public string ControlID
        {
            get;
            private set;
        }

        public string Value { get; private set; }

        public GridColumnFilterEventArgs(string filterId, string filterValue)
        {
            ControlID = filterId;
            Value = filterValue;
        }
    }
}
